package com.smartcar.client.util;

import javax.crypto.Cipher;
import java.security.*;

/**
 * RSA加密解密
 * @author : 高文娜大美女
 * @className : RsaUtil
 * @description : 描述说明该类的功能
 * @createTime : 2023/10/25 10:05
 */
public class RsaUtil {
    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPair keyPair = generateKeyPair();

        // 获取公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 模拟客户端加密数据
        String data = "Hello, World!";
        byte[] encryptedData = encrypt(data, publicKey);

        // 模拟服务端解密数据
        String decryptedData = decrypt(encryptedData, privateKey);

        System.out.println("原始数据：" + data);
        System.out.println("加密后的数据：" + new String(encryptedData));
        System.out.println("解密后的数据：" + decryptedData);
    }

    // 生成密钥对
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom();
        keyPairGenerator.initialize(2048, secureRandom);
        return keyPairGenerator.generateKeyPair();
    }

    // 使用公钥加密数据
    public static byte[] encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

    // 使用私钥解密数据
    public static String decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(encryptedData);
        return new String(decryptedData);
    }
}
